<?php

declare (strict_types=1);
namespace App\Model;

use Hyperf\DbConnection\Db;

/**
 * @property int $id
 * @property int $appid
 * @property string $account
 * @property int $type
 * @property int $createtime
 */
class Group extends BaseModel
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'group';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'appid' => 'integer', 'type' => 'integer', 'createtime' => 'integer'];

    /**
     * @param $appid
     * @param $array
     * @return string
     */
    public static function createGroup($appid,$array)
    {
        if (!isset($array['account']) || empty($array['account']))
            return 'account is null';

        $title  = $array['title'] ?? '';
        $avatar = $array['avatar'] ?? '';

        $time = time();
        Db::beginTransaction();
        try {
            $data = [
                'appid' => $appid,
                'account' => $array['account'],
                'type' => 1,
                'title'   => $title,
                'avatar'  => $avatar,
                'createtime' => $time,
            ];
            $g_id = self::insertGetId($data);

            $data_user = [
                'g_id'    => $g_id,
                'account' => $array['account'],
                'type'    => 1,
                'addtime' => $time,
            ];
            GroupUser::insert($data_user);

            Db::commit();
            return [
                'g_id'=> $g_id,
                'owner_account'=>$array['account'],
                'title' => $title,
                'avatar' => $avatar,
            ];
        }catch (\Exception $e){
            Db::rollBack();
            return $e->getMessage();
        }
    }

    /**
     * 获取群主列表
     * @param int $appid
     * @param $post
     * @return array|string
     */
    public static function listGroup(int $appid, $post)
    {
        $account = $post['account'] ?? '';
        $page    = $post['page'] ?? 1;
        $size    = $post['size'] ?? self::$_p_size;


        if (empty($account))
            return 'account is null';

        $where = [
            'group.appid' => $appid,
            'group_user.account' => $account,
        ];

        $info = self::where($where)
            ->select(['group_user.g_id','group_user.type','group.title','group.avatar','group_user.addtime'])
            ->rightJoin('group_user','group_user.g_id','=','group.id')
            ->offset(self::p_offset($page,$size))
            ->limit(self::p_size($size))
            ->orderByDesc('createtime')
            ->get()
            ->toArray();

        foreach ($info as &$val)
        {
            switch ($val['type'])
            {
                case 0:
                    $val['type'] = '成员';
                    break;
                case 1:
                    $val['type'] = '群主';
                    break;
                case 2:
                    $val['type'] = '管理员';
                    break;
            }

        }
        return $info;
    }


    public static function getMsgGroup(array $array)
    {
        $g_id = $array['g_id'] ?? '';
        $page = $array['page'] ?? 1;
        $size = $array['size'] ?? self::$_p_size;
        if (empty($g_id))
            return 'g_id is null';

        $offet = self::p_offset($page,$size);
        $size  = self::p_size($size);

        $sql = "select a.g_id,a.account,a.content,a.created_at,b.username,b.avatar from hyy_group_msg a left join hyy_user_bind b on b.account=a.account and b.appid=? where a.g_id=? order by a.id desc limit $offet,$size";

        $list = Db::select($sql, [$array['appid'], $g_id]);

        if ($list){
            foreach ($list as &$val)
            {
                $val->content = unserialize($val->content);
            }
            return $list;
        }
        return [];
    }

    /**
     * 删除群
     * @param $appid
     * @param $g_ids
     * @return string
     */
    public static function delGroup($appid, $g_ids)
    {
        if (empty($g_ids))
        {
            return 'g_id is null';
        }

        if (!is_array($g_ids))
        {
            $g_ids = json_decode($g_ids, true);
        }

        $succ = [];
        $fail = [];
        Db::beginTransaction();
        try {
            foreach ($g_ids as $g_id)
            {

                if(self::where(['appid'=>$appid, 'id'=>$g_id])->delete() > 0)
                {
                    // 并删除群消息
                    GroupMsg::where(['g_id'=>$g_id])->delete();
                    // 删除群成员
                    GroupUser::where(['g_id'=>$g_id])->delete();

                    $succ[] = $g_id;
                }else{
                    $fail[] = $g_id;
                }

            }

            Db::commit();

            return ['succ' => $succ, 'fail' => $fail];
        }catch (\Exception  $exception)
        {
            Db::rollBack();
            return $exception->getMessage();
        }




    }

    /**
     * 修改群信息
     * @param $appid
     * @param $array
     * @return string
     */
    public static function updateGroup($appid, $array)
    {
        $g_id   = isset($array['g_id']) ? intval($array['g_id']) : 0;
        $title  = $array['title'] ?? '';
        $avatar = $array['avatar'] ?? '';

        if ($g_id <= 0)
        {
            return 'g_id is null';
        }

        $where = ['appid'=>$appid,'id'=>$g_id];

        $group = self::where($where)->first(['id','title','avatar']);
        if (!$group)
            return '群组不存在或已解散';

        $update = [];

        if (!empty($title))
            $update['title'] = $title;

        if(!empty($avatar))
            $update['avatar'] = $avatar;

        if (empty($update))
        {
            return '名称 和 头像 必填一个';
        }

        if (self::where($where)->update($update) > 0)
        {
            return [
                'new' => $update,
                'old' => $group
            ];
        }
        return '修改失败';

    }

    /**
     *
     * @param $appid
     * @param $g_id
     * @param $to_account
     * @return array|string
     */
    public static function changeOwner($appid, $g_id, $to_account)
    {
        $g_id = intval($g_id);

        if ($g_id <= 0)
            return 'g_id is null';
        if (empty($to_account))
            return 'to_account is null';

        $where = ['appid'=>$appid,'id'=>$g_id];

        $group = self::where($where)->first(['account']);
        if (!$group)
            return '群组不存在或已解散';

        if ($to_account == $group->account)
            return '当前用户已是群主';

        $user = UserBind::where(['appid'=>$appid,'account'=>$to_account])->first();
        if (!$user)
            return '当前用户未登录IM系统';

        $group_user = GroupUser::where(['g_id'=>$g_id,'account'=>$to_account])->first();
        if (!$group_user)
            return '当前用户不在群组中，请先添加';

        Db::beginTransaction();
        try {
            self::where($where)->update(['account'=>$to_account]);

            // 修改 群员在组的类型
            GroupUser::where(['g_id'=>$g_id,'account'=>$group->account])->update(['type'=>0]);
            GroupUser::where(['g_id'=>$g_id,'account'=>$to_account])->update(['type'=>1]);

            Db::commit();

            return [
                'g_id'        => $g_id,
                'new_account' => $to_account,
                'old_account' => $group->account
            ];

        }catch (\Exception $exception)
        {
            Db::rollBack();
            return $exception->getMessage();
        }
    }


}